package com.liuke.study.thread;

import jdk.nashorn.internal.ir.ReturnNode;

/**
 * TODO
 *
 * @author wangjwy
 * @date 2019/10/18 14:21
 * @since 1.0.0
 */
public class Test3 {
	/*
		编写程序实现,子线程循环3次,接着主线程循环5次,接着再子线程循环3次,主线程循环5次,如此反复,循环3次.
	*/

	public static void main(String[] args) throws InterruptedException {
		Object lockA = new Object();
		Object lockB = new Object();

		MyThread myThread1 = new MyThread(5, lockA, lockB, "main-Thread");
		MyThread myThread2 = new MyThread(3, lockB, lockA, "sub-Thread");
		myThread2.start();
		Thread.sleep(200);
		myThread1.start();
		Thread.sleep(3000);
	}

	static class MyThread extends Thread {

		private int count;

		private Object lockA;
		private Object lockB;

		public MyThread(Integer count, Object lockA, Object lockB, String name) {
			super(name);
			this.count = count;
			this.lockA = lockA;
			this.lockB = lockB;

		}

		boolean flag = false;

		@Override
		public void run() {
			int icount = 0;
			while (icount < 3) {
				synchronized (lockB){
					synchronized (lockA) {
						for (int i = 0; i < count; i++) {
							System.out.println("线程名: " + Thread.currentThread().getName() + " 次数: " + i);
						}
						lockA.notify();
					}
					try {
						if (icount < 2) {
							lockB.wait();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				icount++;
			}
		}
	}
}
